package com.ly.common.servlet;

import com.google.gson.Gson;
import com.ly.common.bean.Result;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 *  	封装的Servlet
 *  	/login.s   1个地址对应一个servlet
 *  	/BaseServlet/*  N个地址对应一个servlet
 *  	/BaseServlet/abc, /BaseServlet/eft  /BaseServlet
 */
// 抽象类
public abstract class BaseServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected Gson gson = new Gson();

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取地址中的方法名
        String path = request.getRequestURL().toString();
        path = path.replaceAll(".+?/(\\w*)(\\.\\w+)?$", "$1");// 贪婪模式

        try {
            //执行公共代码
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json;charset=utf-8");
            // 通过反射查找对应方法, this.getClass() 获取当前对象的类对象
            Method m = this.getClass().getDeclaredMethod(path, HttpServletRequest.class, HttpServletResponse.class);
            // 执行方法
            System.out.println("执行：" + m);
            try {
                m.setAccessible(true);
                Object ret = m.invoke(this, request, response);
                if (ret != null) {
                    response.getWriter().append(gson.toJson(ret));
                }
            } catch (InvocationTargetException e) {
                e.printStackTrace();
                response.getWriter().append(gson.toJson(Result.failure("系统异常, 请联系管理员", null)));
            }
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException e) {
            throw new RuntimeException("方法名错误：" + path, e);
        }

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

